package threads

import database.ConnectionPool
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import java.sql.SQLException
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.ThreadPoolExecutor


/**
 * 每分钟的任务
 *
 * @param threadPool 访问B站API的线程所在的线程池
 * @param connectionPool 数据库连接池，用于获取当前任务列表
 * @param queue 阻塞队列，用于“生产者-消费者”模式的资源沟通
 * @author Jingyu
 */
class MinuteTask(
    private val threadPool: ThreadPoolExecutor,
    private val connectionPool: ConnectionPool,
    private val queue: ArrayBlockingQueue<MediaListResponse>
) : Thread() {
    private val selectSql = "SELECT * FROM task_list;"
    private val logger: Logger = LogManager.getLogger(Main::class.java)

    /**
     * 从数据库中获取当前任务列表
     */
    private fun getAidList(): MutableList<Int> {
        val connection = connectionPool.getConnection()
        try {
            val prSt = connection.prepareStatement(selectSql).apply {
                executeQuery()
            }
            val resultSet = prSt.resultSet
            val taskList = mutableListOf<Int>()
            while (resultSet.next()) {
                taskList.add(resultSet.getInt("aid"))
            }
            prSt.close()
            logger.info("成功获取任务列表，当前任务共${taskList.size}个。")
            return taskList
        } catch (e: SQLException) {
            logger.error("获取任务列表失败！", e)
        } finally {
            connectionPool.releaseConnection(connection)
        }
        return mutableListOf() // 添加一个默认的返回值
    }

    override fun run() {
        logger.debug("分钟线程成功启动")

        // 1. 获取任务列表
        val aidList = getAidList()

        // 2.用线程池去执行任务
        val cnt = aidList.size / 10 // 我计划每个ApiThread负责10个AV号
        for (i in 0 until cnt) {
            threadPool.execute(ApiThread(aidList.subList(i * 10, i * 10 + 10), queue))
        }
        // 处理剩余的元素
        if (aidList.size % 10 != 0) {
            threadPool.execute(ApiThread(aidList.subList(cnt * 10, aidList.size), queue))
        }
        logger.debug("分钟线程已成功启动各API线程")
    }
}